Skip to content

Add unit tests for RequestId and Exception Handling Middlewares - #128

Closed
namidanam wants to merge 1 commit into
FailproofAI:mainfrom
namidanam:add-middleware-tests
Closed

Add unit tests for RequestId and Exception Handling Middlewares #128
namidanam wants to merge 1 commit into
FailproofAI:mainfrom
namidanam:add-middleware-tests

Conversation

@namidanam

Copy link
Copy Markdown
Contributor

This PR adds pytest-based unit tests for the RequestIdMiddleware and UnhandledExceptionsMiddleware. The tests verify correct request ID generation, preservation, replacement of invalid IDs, and proper JSON error responses on unhandled exceptions

@coderabbitai

coderabbitai Bot commented Aug 1, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Summary by CodeRabbit

  • Tests
    • Added tests to verify that request ID headers are correctly generated, echoed, or replaced as needed.
    • Added tests to ensure unhandled exceptions are properly caught and return consistent error responses.

Walkthrough

A new test module has been introduced to validate the behavior of two FastAPI middlewares: RequestIdMiddleware and UnhandledExceptionsMiddleware. The module sets up a test FastAPI application, defines relevant endpoints, and implements tests to check request ID handling and unhandled exception responses.

Changes

Cohort / File(s) Change Summary
FastAPI Middleware Tests
api-server/tests/test_middlewares.py
Added a new test module that sets up a FastAPI app with RequestIdMiddleware and UnhandledExceptionsMiddleware, provides dummy endpoints, and implements tests for request ID header management and unhandled exception handling.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

In the warren of code, tests now appear,
For headers and errors, the rabbits cheer.
Request IDs hop, exceptions are caught,
Each response checked, as it ought.
With every new test, the garden grows bright—
Bugs beware, for all is in sight!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bedae6d and 6d8cfc4.

📒 Files selected for processing (1)
  • api-server/tests/test_middlewares.py (1 hunks)
🔇 Additional comments (7)
api-server/tests/test_middlewares.py (7)

1-9: LGTM! Well-organized imports.

The imports are properly structured with standard library, third-party, and local imports clearly separated. All imported modules are used in the test implementation.


11-19: LGTM! Simple and effective test endpoints.

The dummy endpoints are well-designed for testing purposes:

  • ok_endpoint provides a clean success case
  • fail_endpoint reliably triggers exception handling
  • Both follow FastAPI async function conventions

21-38: LGTM! Well-structured test fixture.

The fixture setup is excellent:

  • Clear documentation explaining its purpose
  • Proper middleware ordering with helpful comment
  • Correct route registration
  • Appropriate use of TestClient for ASGI testing

40-51: LGTM! Comprehensive test for auto-generation.

The test effectively validates request ID auto-generation:

  • Clear test documentation
  • Proper validation of UUID format using uuid.UUID()
  • Confirms response body remains unchanged
  • Good coverage of the auto-generation scenario

53-60: LGTM! Proper validation of ID preservation.

The test correctly validates that valid request IDs are preserved:

  • Uses uuid.uuid4() for generating valid test data
  • Proper header passing in the request
  • Exact match validation ensures no modification occurs

62-70: LGTM! Effective validation of invalid ID replacement.

The test properly validates replacement of invalid request IDs:

  • Uses clearly invalid test data ("invalid-id")
  • Confirms replacement occurred with inequality check
  • Validates replacement is a proper UUID format

72-84: LGTM! Comprehensive exception handling validation.

The test thoroughly validates unhandled exception processing:

  • Proper triggering of exception via /fail endpoint
  • Correct status code validation (500)
  • Flexible error field checking (error or detail)
  • Ensures request ID header persists through error handling
✨ Finishing Touches
  • 📝 Docstrings were successfully generated. (🔄 Check again to generate docstrings again)
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai Bot added a commit that referenced this pull request Aug 1, 2025
Docstrings generation was requested by @NiveditJain.

* #128 (comment)

The following files were modified:

* `api-server/tests/test_middlewares.py`
@coderabbitai

coderabbitai Bot commented Aug 1, 2025

Copy link
Copy Markdown
Contributor

Note

Generated docstrings for this pull request at #129

NiveditJain

This comment was marked as duplicate.

@NiveditJain NiveditJain left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a CI/CD pipeline to run these test while commit and pull request events.

We should probably add these in the same PR.

Comment on lines +30 to +31
app.add_middleware(UnhandledExceptionsMiddleware)
app.add_middleware(RequestIdMiddleware)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's a good idea we test these middlewares separately instead of testing them together.

assert new_rid != "invalid-id" # Confirm the invalid ID was replaced
uuid.UUID(new_rid) # Confirm replacement is a valid UUID

def test_unhandled_exception_caught(client):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this to a different file, let's keep the test per logical unit separately

assert resp.status_code == 500 # Middleware converts error to HTTP 500 response

body = resp.json()
assert "error" in body or "detail" in body # Error info present in JSON response body

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a fixed error body, I think it is better to assert that the whole body in asset equal condition.

Ref: https://github.com/exospherehost/exospherehost/blob/main/api-server%2Fapp%2Fmiddlewares%2Funhandled_exceptions_middleware.py#L25-L28

@namidanam namidanam closed this Aug 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants